package flowcontrol.countdownlatch;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 描述：工厂中质检，5个工人检查，所有工人检查完毕，质检员才能进行下一步
 */

public class CountDownLatchDemo01 {
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        ExecutorService service = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            service.submit(()->{
                try {
                    Thread.sleep((long) (Math.random()*10000));
                    System.out.println("工人" + Thread.currentThread().getName() + "检查完毕");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        System.out.println("等待5个工人检查完毕...");
        try {
            countDownLatch.await();// 主线程阻塞，等待countDownLatch计数器为0
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("5个工人检查完毕，质检员可以进行下一步");
    }
}
